<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\model\member;

use buwang\base\BaseModel;
use think\Exception;

class Wallet extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'member_wallet';

    public function Member()
    {
        return $this->belongsto(\app\common\model\Member::class, 'member_id', 'id', [], 'LEFT');
    }

    public static function getMoney($member_id)
    {
        return self::where(['member_id' => $member_id])->value('money') ?: 0;
    }

    public static function changeMoney($member_id, $type, $money, $memo, $money_type = 'money')
    {
        if (!in_array($money_type, ['money', 'freeze_money'])) throw new Exception('资金类型有误');

        if ($money_type == 'money' && !in_array($type, ['admin', 'recharge', 'miniapp', 'cloud_packet', 'plugin'])) throw new Exception('余额变更类型有误');
        if ($money_type == 'freeze_money' && !in_array($type, ['admin'])) throw new Exception('冻结余额变更类型有误');

        if ($money == 0) throw new Exception('金额不能为0');

        $wallet = self::where(['member_id' => $member_id])->find();
        if (!$wallet) {
            $walletParam = [
                'member_id' => $member_id
            ];
            $wallet = self::create($walletParam);
        }

        $value = $money;
        $before = $wallet[$money_type];
        $after = bcadd($before, $value, 2);

        if ($after < 0) throw new Exception('余额不足');

        //变更余额
        $wallet->$money_type = $after;
        $wallet->save();
        //生成记录
        WalletBill::create(compact('member_id', 'type', 'value', 'before', 'after', 'memo', 'money_type'));

        return true;
    }
}